package ;
import neko.Sys;
import neko.Lib;
import neko.io.Path;
import neko.FileSystem;








class Files {
    static public function get(args:Array<String>):Array<String> {
        for(i in 0...(args.length>>1)) {
            args[i<<1] = new Path(args[i<<1]).toString();
            var snd = (i<<1)+1 < args.length;
            if(snd)
                args[(i<<1)+1] = new Path(args[(i<<1)+1]).toString();
            
            if(!FileSystem.exists(args[i<<1])) {
                Lib.println("Directory '"+args[i<<1]+"' does not exist.");
                Sys.exit(1);
            }
            if(!FileSystem.isDirectory(args[i<<1])) {
                Lib.println("'"+args[i<<1]+"' is not a directory.");
                Sys.exit(1);
            }
            
            if(!snd) continue;
            
            var dir = args[(i<<1)+1];
            if(!FileSystem.exists(dir)) {
                var dirs = [dir];
                while(dirs.length>0) {
                    var dir = dirs.pop();
                    if(FileSystem.exists(dir)) {
                        if(!FileSystem.isDirectory(dir)) {
                            Lib.println("OUT DIR ERROR");
                            Sys.exit(1);
                        }else continue;
                    }
                    
                    try {
                        FileSystem.createDirectory(dir);
                    }catch(e:Dynamic) {
                        dirs.push(dir);
                        var c1 = dir.lastIndexOf('/');
                        var c2 = dir.lastIndexOf('\\');
                        var subdir =
                            if(c1<c2) dir.substr(0,c2)
                            else if(c2<c1) dir.substr(0,c1)
                            else null;
                        if(subdir==null) break;
                        dirs.push(subdir);
                    }
                }

                if(!FileSystem.exists(dir)) {
                    Lib.println("Unable to create directory '"+dir+"'");
                    Sys.exit(1);
                }
            }else if(!FileSystem.isDirectory(dir)) {
                Lib.println("'"+dir+"' is not a directory.");
                Sys.exit(1);
            }
        }
        
        var files = [];
        for(i in 0...(args.length>>1)) {
            var paths = [args[i<<1]];
            while(paths.length>0) {
                var path = paths.pop();
                for(i in FileSystem.readDirectory(path)) {
                    var p = new Path(path+'/'+i).toString();
                    if(FileSystem.kind(p)==kfile) {
                        if(Path.extension(p)=='cx') files.push(p);
                    }else if(FileSystem.isDirectory(p))
                        paths.push(p);
                }
            }
        }
        return files;
    }
}
